<template>
  <page-header title="购物车" background="F7F0E6"></page-header>
  <view class="page-cart">
    <view class="address">
      <view class="address-name" @tap="gotoAddressList">
        <image class="icon" src="../../static/img/location.png"></image>
        <text class="text-overflow-clamp-2">
          {{ defaultAddrStr || '暂无地址' }}
        </text>
      </view>
      <!-- <view class="edit" @tap="editCart">
        {{ isEditCart ? '退出管理' : '管理' }}
      </view> -->
    </view>
    <view class="cart">

      <block v-for="(shopItem, shopIndex) in Data.shopCarts" :key="shopIndex">
        <uni-swipe-action>
          <uni-swipe-action-item ref="swiper" v-for="(prodItem, prodIndex) in shopItem.shopCartItem" :key="prodIndex"
            :right-options="options" @click="handleEditOper(prodItem.cartItemId)">
            <view class="cart-item" @tap="toProdDetail(prodItem.spuId)">
              <image class="background" :src="addDomain('/static/cart-item.png')"></image>
              <view class="content">
                <view class="item-header">
                  <view>
                    <image class="icon" src="/static/images/shop.png" />
                    {{ shopItem.shopName }}
                  </view>
                  <uni-icons @tap.stop="handleProdItemSelect(shopIndex, prodIndex)" type="checkbox" color="#DA9974"
                    :size="24" v-if="prodItem.isChecked ? true : false"></uni-icons>
                  <uni-icons @tap.stop="handleProdItemSelect(shopIndex, prodIndex)" type="circle" color="#DA9974"
                    :size="24" v-else></uni-icons>
                </view>
                <view class="item-body">
                  <image :src="prodItem.imgUrl" class="left" mode="aspectFill"></image>
                  <view class="right">
                    <view class="text-overflow-clamp-2">{{ prodItem.spuName }}</view>
                    <view class="sku">
                      <view class="skuItem">{{ prodItem.skuName }}</view>
                    </view>
                    <price-point :price="prodItem.priceFee" :point="prodItem.pointPrice" :size="30"></price-point>
                    <view class="number-box" v-if="prodItem.needIdCard != 1" @tap.stop="">
                      <view class="minus" @tap.stop="changeNumber(shopIndex, prodIndex, -1)">-</view>
                      <input disabled v-model="prodItem.count" type="number" class="number" maxlength="4">
                      <view class="plus" @tap.stop="changeNumber(shopIndex, prodIndex, 1)">+</view>
                    </view>
                  </view>
                </view>
                <view class="viewer" v-if="prodItem.needIdCard == 1">
                  <view class="header">
                    <view class="group">
                      <view class="title">
                        实名观演人
                      </view>
                    </view>
                  </view>
                  <view class="item" v-for="(cardItem, index) in handleIdCards(prodItem.idCards)" :key="index">
                    <view>
                      <view class="name">{{ queryName(cardItem) }}</view>
                      <view class="card">{{ queryType(cardItem) }} {{ handleIdCard(cardItem) }}</view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </uni-swipe-action-item>
        </uni-swipe-action>
      </block>

      <empty-img v-if="!shopCarts.length" padding="0">
        <template #text>
          购物车空空的，去逛逛吧~
        </template>
        <template #button>
          <view @tap="toIndex">去商城首页</view>
        </template>
      </empty-img>


    </view>
    <view class="bottom-box">
      <view class="price-total">
        合计：
        <price-point :price="Data.totalMoney" :point="Data.totalPointPrice"></price-point>
      </view>
      <view class="button-group">
        <view class="check-all" @tap="handleSelectAll">
          <uni-icons type="circle" color="#DA9974" :size="24" v-if="!allChecked"></uni-icons>
          <uni-icons type="checkbox" color="#DA9974" :size="24" v-else></uni-icons>
          全选
        </view>
        <view class="warn-button" @tap="handleEditOper(-1)" v-if="isEditCart">
          删除所选
        </view>
        <view class="rgb-button" @tap="submitOrder" v-else>
          结算({{ selectedCounts }})
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
  import {
    onShow,
    onUnload
  } from '@dcloudio/uni-app';
  const Data = reactive({
    isEditCart: false, // 编辑购物车
    isShowSkuPopup: false, // sku弹窗显示
    idCardList: [],
    shopCarts: [],
    totalMoney: 0,
    totalPointPrice: 0,
    allChecked: false, // 全选状态
    prodInfo: {},
    skuList: [],
    skuGroup: {},
    findSku: true,
    skuShowType: 0,
    defaultSku: undefined,
    selectedProp: [],
    selectedPropObj: {},
    selectedProperties: '',
    propKeys: [],
    allProperties: [],
    oldSkuId: null,
    shopIndex: 0,
    prodIndex: 0,
    reqItemList: [], // 勾选的项目
    selectedCounts: 0,
    prodDiscounts: [],
    spuId: '',
    curBasketItemCheck: '',
    operBasketItem: '',
    defaultAddrStr: '', // 默认地址
    addrId: 0
  })
  const {
    isEditCart,
    isShowSkuPopup,
    shopCarts,
    totalMoney,
    totalPointPrice,
    allChecked,
    prodInfo,
    skuGroup,
    idCardList,
    findSku,
    defaultSku,
    selectedProp,
    selectedPropObj,
    propKeys,
    allProperties,
    selectedCounts,
    defaultAddrStr,
    addrId
  } = toRefs(Data)

  const options = ref([{
    text: '移除购物车',
    style: {
      backgroundColor: '#94673D'
    }
  }])

  onShow(() => {
    uni.getStorage({
      key: 'cloudAddress'
    }).then(res => {
      if (res.data != '') {
        Data.addrId = res.data
      }
    }).catch(res => {}).finally(getDefaultAddrStr())
    // 获取用户购物车信息
    getCartInfo()
  })

  onUnload(() => {
    uni.setStorageSync("cloudAddress", '')
  })
  /**
   * 提交订单
   */
  const submitOrder = () => {
    if (!Data.selectedCounts) {
      uni.showToast({
        title: '请选择商品！',
        duration: 2000,
        icon: 'none'
      })
      return
    }
    const basketIds = []
    Data.shopCarts.forEach(shopItem => {
      shopItem.shopCartItem.forEach(prodItem => {
        if (prodItem.checked) {
          basketIds.push(prodItem.cartItemId)
        }
      })
    })
    uni.navigateTo({
      url: '/pages/submit-order/submit-order?orderEntry=0&addrId=' + Data.addrId +
        '&dvyType=3' // dvyType 配送类型 1:快递 2:自提 3：无需快递 4:同城配送
    })
  }

  /**
   * 编辑状态的操作
   * @param operType {Number} 1添加收藏  -1删除
   */
  const handleEditOper = (id) => {
    const selectIds = []
    selectIds.push(id)
    uni.showModal({
      title: '提示',
      content: '确认要删除选中的商品吗？',
      success: function(res) {
        if (res.confirm) {
          http.request({
            url: '/mall4cloud_product/a/shop_cart/delete_item',
            method: 'DELETE',
            data: selectIds
          }).then(() => {
            uni.showToast({
              title: '删除成功',
              duration: 2000
            })
            getCartInfo()
          })
        }
      }
    })
  }
  // const handleEditOper = (operType) => {
  //   const selectIds = []
  //   const shopCarts = Data.shopCarts
  //   shopCarts.forEach(shopItem => {
  //     shopItem.shopCartItem.forEach(prodItem => {
  //       if (prodItem.checked) {
  //         selectIds.push(prodItem.cartItemId)
  //       }
  //     })
  //   })
  //   uni.showModal({
  //     title: '提示',
  //     content: '确认要删除选中的商品吗？',
  //     success: function (res) {
  //       if (res.confirm) {
  //         http.request({
  //           url: '/mall4cloud_product/a/shop_cart/delete_item',
  //           method: 'DELETE',
  //           data: selectIds
  //         }).then(() => {
  //           uni.showToast({
  //             title: '删除成功',
  //             duration: 2000
  //           })
  //           if (operType === -1) {
  //             getCartInfo()
  //             if (operType != 1) {
  //               //cartCount.getCartCount()
  //             }
  //           }
  //         })
  //       }
  //     }
  //   })
  // }

  /**
   * 商品数量加减
   */
  const changeNumber = (shopIndex, prodIndex, num) => {
    let curItem
    let reqData = {}
    if (num) {
      curItem = Data.shopCarts[shopIndex].shopCartItem[prodIndex]
      reqData = {
        count: num,
        shopCartItemId: curItem.cartItemId,
        skuId: curItem.skuId,
        spuId: curItem.spuId,
        idCards: ''
      }
    }
    const params = {
      url: '/mall4cloud_product/a/shop_cart/change_item',
      method: 'POST',
      data: reqData
    }
    if (num === -1 && curItem.count === 1) {
      uni.showModal({
        title: '提示',
        content: '要从购物车移除此商品吗？',
        success: function(res) {
          if (res.confirm) {
            http.request(params).then(() => {
              getCartInfo()
              if (num != 0) {
                //cartCount.getCartCount()
              }
            })
          }
        }
      })
    } else {
      http.request(params).then(() => {
        getCartInfo()
        if (num != 0) {
          //cartCount.getCartCount()
        }
      })
    }
  }

  /**
   * 获取用户购物车信息
   */
  const getCartInfo = () => {
    http.request({
      url: '/mall4cloud_product/a/shop_cart/info',
      method: 'GET'
    }).then((res) => {
      const shopCarts = res.shopCarts
      Data.totalPointPrice = 0
      if (!Data.reqItemList.length) { // 初次请求
        // 所有商品添加勾选状态
        shopCarts.forEach(shopItem => {
          shopItem.shopCartItem.forEach(prodItem => {
            prodItem.checked = !!prodItem.isChecked
            if (prodItem.checked) {
              Data.totalPointPrice += prodItem.totalPointPrice
            }
          })
        })
      } else { // 修改购物车
        shopCarts.forEach(shopItem => {
          shopItem.shopCartItem.forEach(prodItem => {
            if (prodItem.isChecked == 1) {
              prodItem.checked = true
              Data.totalPointPrice += prodItem.totalPointPrice
            }
          })
        })
      }
      Data.shopCarts = shopCarts
      Data.totalMoney = res.totalMoney
      checkAllSelected()
      calSelectedCounts()
    })
  }

  /**
   * 检查全选状态
   */
  const checkAllSelected = () => {
    let allChecked = true
    const shopCarts = Data.shopCarts
    shopCarts.forEach(shopCart => {
      let shopChecked = true
      const cItems = shopCart.shopCartItem
      for (let j = 0; j < cItems.length; j++) {
        if (!cItems[j].isChecked) {
          shopChecked = false
          allChecked = false
        }
        cItems[j].checked = !!cItems[j].checked
      }
      shopCart.checked = shopChecked
    })
    Data.allChecked = allChecked
    Data.shopCarts = shopCarts
  }

  /**
   * 每一个商品的 勾选/取选
   */
  const handleProdItemSelect = (shopIndex, prodIndex) => {
    const shopCarts = Data.shopCarts
    const cartItem = shopCarts[shopIndex].shopCartItem[prodIndex]
    const checked = cartItem.isChecked
    cartItem.checked = !checked
    Data.shopCarts = shopCarts
    checkAllSelected()
    // 重新设置勾选列表数据
    Data.reqItemList = []
    Data.reqItemList.push({
      isChecked: cartItem.checked ? 1 : 0,
      shopCartItemId: cartItem.cartItemId
    })
    calTotalPrice()
  }

  /**
   * 点击全选
   */
  const handleSelectAll = () => {
    let allChecked = Data.allChecked
    const shopCarts = Data.shopCarts
    allChecked = !allChecked
    Data.reqItemList = []
    shopCarts.forEach(shopItem => {
      shopItem.checked = allChecked
      shopItem.shopCartItem.forEach(item => {
        if (item.isChecked !== allChecked) {
          Data.reqItemList.push({
            isChecked: allChecked ? 1 : 0,
            shopCartItemId: item.cartItemId
          })
        }
      })
    })
    Data.allChecked = allChecked
    Data.shopCarts = shopCarts
    calTotalPrice()
    calSelectedCounts()
  }
  /**
   * 计算购物车选中的商品项的数量
   */
  const calSelectedCounts = () => {
    // 计算购物车勾选的项目数量
    let sum = 0
    Data.shopCarts.forEach(shopItem => {
      shopItem.shopCartItem.forEach(prodItem => {
        if (prodItem.isChecked) {
          sum++
        }
      })
    })
    Data.selectedCounts = sum
  }

  /**
   * 计算价格
   */
  const calTotalPrice = () => {
    const params = {
      url: '/mall4cloud_product/a/shop_cart/check_items',
      method: 'POST',
      data: Data.reqItemList
    }
    http.request(params).then(() => {
      getCartInfo()
    })
  }

  // 编辑购物车
  const editCart = () => {
    Data.isEditCart = !Data.isEditCart
  }

  // 显示Sku弹窗
  const showSkuPopup = (shopIndex, prodIndex) => {
    Data.shopIndex = shopIndex
    Data.prodIndex = prodIndex
    const cartItem = Data.shopCarts[shopIndex].shopCartItem[prodIndex]
    const oldSkuId = cartItem.skuId
    Data.oldSkuId = oldSkuId
    getProdInfo(cartItem.spuId)
  }

  /**
   * sku弹窗确认
   */
  const skuPopupConfirm = () => {
    if (!Data.findSku) {
      uni.showToast({
        title: '所选规格无货',
        duration: 2000,
        icon: 'none'
      })
      return
    }
    if (Data.defaultSku.skuId === Data.oldSkuId) {
      Data.isShowSkuPopup = false
      return
    }
    const cartItem = Data.shopCarts[Data.shopIndex].shopCartItem[Data.prodIndex]
    const params = {
      url: '/mall4cloud_product/a/shop_cart/change_item',
      method: 'POST',
      data: {
        oldSkuId: Data.oldSkuId,
        shopCartItemId: cartItem.cartItemId,
        count: cartItem.count,
        skuId: Data.defaultSku.skuId,
        spuId: cartItem.spuId
      }
    }
    http.request(params).then(() => {
      Data.isShowSkuPopup = false
      getCartInfo()
    })
  }

  /**
   * 获取商品详情
   */
  const getProdInfo = (spuId) => {
    uni.showLoading()
    const params = {
      url: '/mall4cloud_product/ua/spu/prod_info',
      method: 'GET',
      data: {
        spuId
      }
    }
    http.request(params).then((res) => {
      Data.prodInfo = res
      Data.skuList = res.skus
      groupSkuProp(res.skus, res.priceFee)
      uni.hideLoading()
    })
  }

  /**
   * 组装SKU
   */
  const groupSkuProp = (skuList) => {
    if (skuList.length == 1 && skuList[0].properties == '') {
      Data.defaultSku = skuList[0]
      return
    }
    const skuGroup = {}
    const allProperties = []
    const propKeys = []
    const selectedPropObj = {}
    let defaultSku = null
    for (let i = 0; i < skuList.length; i++) {
      let isDefault = false
      if (!defaultSku && skuList[i].skuId == Data.oldSkuId) { // 找到和商品价格一样的那个SKU，作为默认选中的SKU
        defaultSku = skuList[i]
        isDefault = true
      }
      const properties = skuList[i].properties // 版本:公开版;颜色:金色;内存:64GB
      allProperties.push(properties)
      const propList = properties.split(';') // ["版本:公开版","颜色:金色","内存:64GB"]
      for (let j = 0; j < propList.length; j++) {
        const propval = propList[j].split(':') // ["版本","公开版"]
        let props = skuGroup[propval[0]] // 先取出 版本对应的值数组
        // 如果当前是默认选中的sku，把对应的属性值 组装到selectedProp
        if (isDefault) {
          propKeys.push(propval[0])
          selectedPropObj[propval[0]] = propval[1]
        }

        if (props == undefined) {
          props = [] // 假设还没有版本，新建个新的空数组
          props.push(propval[1]) // 把 "公开版" 放进空数组
        } else {
          if (props.indexOf(propval[1]) === -1) { // 如果数组里面没有"公开版"
            props.push(propval[1]) // 把 "公开版" 放进数组
          }
        }
        skuGroup[propval[0]] = props // 最后把数据 放回版本对应的值
      }
    }
    if (Data.oldSkuId) {
      skuList.forEach(skuItem => {
        if (skuItem.skuId === Data.oldSkuId) {
          defaultSku = skuItem
        }
      })
    }
    Data.defaultSku = defaultSku
    Data.propKeys = propKeys
    Data.selectedPropObj = selectedPropObj
    Data.skuGroup = skuGroup
    Data.allProperties = allProperties
    parseSelectedObjToVals(skuList)
    Data.isShowSkuPopup = true
  }

  /**
   * 将已选的 {key:val,key2:val2}转换成 [val,val2]
   */
  const parseSelectedObjToVals = (skuList) => {
    const selectedPropObj = Data.selectedPropObj
    let selectedProperties = ''
    const selectedProp = []
    for (const key in selectedPropObj) {
      selectedProp.push(selectedPropObj[key])
      selectedProperties += key + ':' + selectedPropObj[key] + ';'
    }
    selectedProperties = selectedProperties.substring(0, selectedProperties.length - 1)
    Data.selectedProp = selectedProp
    Data.selectedProperties = selectedProperties
    Data.selectedPropObj = selectedPropObj
    let findSku = false
    for (let i = 0; i < skuList.length; i++) {
      if (skuList[i].properties == selectedProperties) {
        findSku = true
        Data.defaultSku = skuList[i]
        break
      }
    }
    Data.findSku = findSku
  }

  /**
   * 判断当前的规格值 是否可以选
   */
  const isSkuLineItemNotOptional = (allProperties, selectedPropObjPar, key, item, propKeys) => {
    const selectedPropObj = Object.assign({}, selectedPropObjPar)
    let properties = ''
    selectedPropObj[key] = item
    for (let j = 0; j < propKeys.length; j++) {
      properties += propKeys[j] + ':' + selectedPropObj[propKeys[j]] + ';'
    }
    properties = properties.substring(0, properties.length - 1)
    for (let i = 0; i < allProperties.length; i++) {
      if (properties == allProperties[i]) {
        return false
      }
    }
    for (let i = 0; i < allProperties.length; i++) {
      if (allProperties[i].indexOf(item) >= 0) {
        return true
      }
    }
    return false
  }

  /**
   * 规格点击事件
   */
  const toChooseItem = (skuLineItem, key) => {
    Data.selectedPropObj[key] = skuLineItem
    parseSelectedObjToVals(Data.skuList)
  }

  // 隐藏弹窗
  const closePopup = () => {
    Data.isShowSkuPopup = false
  }

  /**
   * 跳转商品详情
   */
  const toProdDetail = (spuId) => {
    const page = getCurrentPages()
    let pathname = `/pages/shop-detail/shop-detail?spuId=${spuId}`
    let arr = page.map(item => item.$page.fullPath)
    const index = page.findIndex(item => item.$page.fullPath === pathname)
    /* 在页面栈中找到时 */
    if (index != -1) {
      const step = page.length - 1 - index
      uni.navigateBack({
        delta: step
      })
    } else {
      uni.navigateTo({
        url: pathname
      })
    }
  }

  /**
   * 获取默认地址的地区信息
   */
  const getDefaultAddrStr = () => {
    uni.showLoading()
    const params = {
      url: '/mall4cloud_user/user_addr/list',
      method: 'GET'
    }
    http.request(params).then(res => {
      if (!res.length) {
        uni.hideLoading()
        return
      }
      if (Data.addrId != 0) {
        const defaultAddr = res.filter((el) => el.addrId == Data.addrId)[0]
        Data.defaultAddrStr = defaultAddr.city + defaultAddr.area + defaultAddr.addr
      } else {
        const defaultAddr = res.filter((el) => el.isDefault)[0]
        Data.defaultAddrStr = defaultAddr.city + defaultAddr.area + defaultAddr.addr
      }
      uni.hideLoading()
    })
  }

  //处理身份证列表
  const handleIdCards = (arr) => {
    if (arr == "") {
      return []
    }
    return arr.split(',')
  }

  //身份证号码脱敏
  const handleIdCard = (item) => {
    let id = item.split(":")[0]
    return String(id).slice(0, 3) + '********' + String(id).slice(16)
  }

  /**
   * 从观演人列表中获取name
   */
  const queryName = (item) => {
    return item.split(":")[1]
  }

  /**
   * 从item获取类型
   */
  const queryType = (item) => {
    return ['', '身份证', '港澳台居民居住证', '港澳居民来往内地通行证', '台湾居民来往大陆通行证', '护照', '外国人永久居留身份证'][item.split(":")[2]]
  }

  const gotoAddressList = () => {
    uni.navigateTo({
      url: '/pages/address-list/address-list?link=true'
    })
  }

  /**
   * 去首页
   */
  const toIndex = () => {
    uni.redirectTo({
      url: '/pages/mall-index/mall-index'
    })
  }

  // 添加图片域名
  const addDomain = (path) => {
      const resourcesUrl = import.meta.env.VITE_APP_FILE_URL
    if (!path || /^http?:\/\//.test(path)) {
      return path
    } else {
      return resourcesUrl + path
    }
  }
</script>

<style>
  page {
    background-color: #F7F0E6;
    height: 100%;
  }
</style>
<style lang="scss" scoped>
  @use "cart";
</style>
